const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

/**
 * 解决 pnpm workspace 中 Electron 应用打包依赖缺失的问题
 * 该脚本会将所有 workspace 依赖复制到本地 node_modules
 */

const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const workspaceDeps = Object.keys(packageJson.dependencies || {})
  .filter(dep => dep.startsWith('@roasmax/'));

console.log('找到以下 workspace 依赖:', workspaceDeps);

// 确保 node_modules 目录存在
if (!fs.existsSync('node_modules')) {
  fs.mkdirSync('node_modules', { recursive: true });
}

// 为每个 workspace 依赖创建符号链接或复制文件
workspaceDeps.forEach(dep => {
  const packageName = dep.replace('@roasmax/', '');
  const sourcePath = path.resolve('../../packages', packageName);
  const targetPath = path.resolve('node_modules', dep);
  
  console.log(`处理依赖: ${dep}`);
  console.log(`源路径: ${sourcePath}`);
  console.log(`目标路径: ${targetPath}`);
  
  if (fs.existsSync(sourcePath)) {
    // 移除现有的目标路径
    if (fs.existsSync(targetPath)) {
      fs.rmSync(targetPath, { recursive: true, force: true });
    }
    
    // 确保目标目录存在
    const targetDir = path.dirname(targetPath);
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    
    try {
      // 在 Windows 上创建目录链接
      if (process.platform === 'win32') {
        execSync(`mklink /J "${targetPath}" "${sourcePath}"`, { stdio: 'inherit' });
      } else {
        // 在 Unix 系统上创建符号链接
        fs.symlinkSync(sourcePath, targetPath, 'dir');
      }
      console.log(`✓ 成功链接 ${dep}`);
    } catch (error) {
      console.warn(`⚠ 无法创建链接，尝试复制文件: ${error.message}`);
      
      // 如果链接失败，则复制整个目录
      try {
        copyDir(sourcePath, targetPath);
        console.log(`✓ 成功复制 ${dep}`);
      } catch (copyError) {
        console.error(`✗ 复制失败: ${copyError.message}`);
      }
    }
  } else {
    console.warn(`⚠ 找不到包源目录: ${sourcePath}`);
  }
});

console.log('依赖处理完成！');

/**
 * 递归复制目录
 */
function copyDir(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }
  
  const entries = fs.readdirSync(src, { withFileTypes: true });
  
  for (let entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);
    
    if (entry.isDirectory()) {
      copyDir(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}
